"use client";

import {
  Group,
  Tree,
  useTree,
  RenderTreeNodePayload,
  Text,
  ActionIcon,
  Tooltip,
} from "@mantine/core";
import {
  IconChevronRight,
  IconChevronDown,
  IconPoint,
  IconReload,
  IconCategoryPlus,
  IconCategoryMinus,
} from "@tabler/icons-react";

import classes from "./IpdTree.module.css";
import {IpdTreeData} from "./IpdTreeData";

// 左侧Icon图标渲染
interface FoldIconProps {
  name: string;
  isFolder: boolean;
  expanded: boolean;
}

function FileIcon({isFolder, expanded}: FoldIconProps) {
  if (isFolder) {
    return expanded ? (
      <IconChevronDown color="var(--mantine-color-indigo-9)" size={14} stroke={2.5} />
    ) : (
      <IconChevronRight color="var(--mantine-color-indigo-9)" size={14} stroke={2.5} />
    );
  }
  if (!isFolder) {
    return <IconPoint color="var(--mantine-color-indigo-9)" size={14} stroke={2.5} />;
  }

  return null;
}

function Leaf({node, expanded, hasChildren, elementProps}: RenderTreeNodePayload) {
  return (
    <Group gap={5} {...elementProps}>
      <FileIcon name={node.value} isFolder={hasChildren} expanded={expanded} />
      <Text size="sm" fw={500}>
        {node.label}
      </Text>
    </Group>
  );
}

export const IpdTree = () => {
  const tree = useTree();
  return (
    <>
      <Group justify="space-between" pb="xs">
        <Text size="sm" fw={500}>
          设备构成
        </Text>
        <Group gap={2}>
          <Tooltip label="刷新列表">
            <ActionIcon size="xs" variant="transparent">
              <IconReload color="var(--mantine-color-indigo-9)" stroke={2} />
            </ActionIcon>
          </Tooltip>
          <Tooltip label="展开全部">
            <ActionIcon size="xs" variant="transparent" onClick={() => tree.expandAllNodes()}>
              <IconCategoryPlus color="var(--mantine-color-indigo-9)" stroke={2} />
            </ActionIcon>
          </Tooltip>
          <Tooltip label="折叠全部">
            <ActionIcon size="xs" variant="transparent" onClick={() => tree.collapseAllNodes()}>
              <IconCategoryMinus color="var(--mantine-color-indigo-9)" stroke={2} />
            </ActionIcon>
          </Tooltip>
        </Group>
      </Group>
      <Tree
        data={IpdTreeData}
        tree={tree}
        classNames={classes}
        selectOnClick
        levelOffset={10}
        renderNode={(payload) => <Leaf {...payload} />}
      />
    </>
  );
};
